import request from '@/utils/request';
import {
  hex_md5
} from '@/utils/md5';
// 灰度  正式需要把v2 换成v1
const baseUrl = process.env.NODE_ENV == 'development' ? 'http://i.yd-jxt.com/v2' : 'http://i.yd-jxt.com/v1'
const imgUrl = process.env.NODE_ENV == 'development' ? '/rat/UploadFileV4' : 'http://i.yd-jxt.com/v1/rat/UploadFileV4'
const apiName = '/rat/EventHandle'

/* GET */
export function axGet(_cmd, _param) {
  return request({
    baseURL: baseUrl,
    url: apiName,
    method: 'get',
    params: {
      json: urlFun(_cmd, _param)
    },
  })
}
/* GET await*/
export async function axGetAwait(_cmd, _param) {
  return await request({
    baseURL: baseUrl,
    url: apiName,
    method: 'get',
    params: {
      json: urlFun(_cmd, _param)
    },
  })
}

/* POST */
export function axPost(_cmd, _param) {
  return request({
    baseURL: baseUrl,
    url: apiName,
    method: 'post',
    data: {
      json: JSON.stringify(urlFun(_cmd, _param))
    },
    transformRequest: [function (data) {
      let ret = ''
      for (let it in data) {
        ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
      }
      return ret
    }],
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
    }
  })
}

/* json function */
export function urlFun(_cmd, _param) {
  var _time = new Date().getTime() + '';
  var _uuid = guid();
  var _noce = noce();
  var _key = 'HTXFV-FH8YX-VCY69-JJGBK-7R6XP';
  var _appJson = {
    "AppId": 1,
    "Cmd": _cmd,
    "Ver": "1.0.0",
    "UnixTime": _time,
    "SessionId": _uuid,
    "Noce": _noce,
    "AppKey": _key,
    "SKey": md5('1', _cmd, _time, _noce, _key, _uuid),
    "JsonParts": _param,
  }
  return _appJson;
}

function md5(appid, cmd, unixTime, noce, key, sessionId) {
  return hex_md5("Company=hzty&Ver=1.0.0&Methord=MD5&AppID=" + appid + "&Cmd=" + cmd + "&UnixTime=" + unixTime + "&Noce=" + noce + "&AppKey=" + key + "&SessionId=" + sessionId);
}

function guid() {
  function S4() {
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
  }
  return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
}

function noce() {
  return parseInt(Math.random() * 100);
}

/* 图片上传 */
export function UploadPictures(query, skey) {
  // console.log(skey,"skey")
  return request({
    baseURL: imgUrl,
    url:  "?" + encodeURI(skey[1]),
    method: 'post',
    data: query,
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8',
      'MultPart-Author-Key': hex_md5(skey[0]),
    }
  })
}

